package com.longyiqun.android.zhihu.Adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dd.CircularProgressButton;
import com.etsy.android.grid.util.DynamicHeightTextView;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;
import com.longyiqun.android.zhihu.Object.Case;
import com.longyiqun.android.zhihu.R;

import java.util.ArrayList;


/**
 * Created by teddy on 3/24/16.
 */
public class MyGridViewAdapter extends ArrayAdapter<Case> {
    // TAG
    private static final String TAG = "MyGridViewAdapter";
    private final ArrayList<String> testResult = new ArrayList<String>();

    // ViewHolder
    static class ViewHolder {
        DynamicHeightTextView txtLineDesc;
        TextView txtLineUrl;
        TextView txtLineHeader;
        CircularProgressButton btnGo;
    }

    // LayoutInflater
    private final LayoutInflater mLayoutInflater;
    // 现在是固定高度，0.218
    //private final Random mRandom;
    // 背景色的ArrayList
    private final ArrayList<Integer> mBackgroundColors;

    // 固定高度，用不到
    //private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();
    // 初始化MyGridViewAdapter
    public MyGridViewAdapter(final Context context, final int textViewResourceId) {
        super(context, textViewResourceId);
        mLayoutInflater = LayoutInflater.from(context);
        // 现在是固定高度，0.218
        //mRandom = new Random();
        // 填充颜色
        mBackgroundColors = new ArrayList<Integer>();
        mBackgroundColors.add(R.color.orange);
        mBackgroundColors.add(R.color.green);
        mBackgroundColors.add(R.color.blue);
        mBackgroundColors.add(R.color.yellow);
        mBackgroundColors.add(R.color.grey);
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {

        final ViewHolder vh;
        if (convertView == null) {
            convertView = mLayoutInflater.inflate(R.layout.grid_view_item, parent, false);
            vh = new ViewHolder();

            vh.txtLineDesc = (DynamicHeightTextView) convertView.findViewById(R.id.txt_desc);
            vh.txtLineUrl = (TextView) convertView.findViewById(R.id.txt_url);
            vh.txtLineHeader = (TextView) convertView.findViewById(R.id.txt_header);
            vh.btnGo = (CircularProgressButton) convertView.findViewById(R.id.btn_go);

            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        // 现在是固定高度，0.218
        //double positionHeight = getPositionRatio(position);
        double positionHeight = 0.318;
        int backgroundIndex = position >= mBackgroundColors.size() ?
                position % mBackgroundColors.size() : position;

        convertView.setBackgroundResource(mBackgroundColors.get(backgroundIndex));

        Log.d(TAG, "getView position:" + position + " h:" + positionHeight);


        vh.txtLineDesc.setHeightRatio(positionHeight);
        vh.txtLineDesc.setText(getItem(position).getId() + ". " + getItem(position).getDesc() + " (" + getItem(position).getType() + ")");

        vh.txtLineUrl.setTextSize(10);
        vh.txtLineUrl.setText(getItem(position).getUrl() + getItem(position).getParams());

        vh.txtLineHeader.setTextSize(10);
        vh.txtLineHeader.setText(getItem(position).getHeaders());


        vh.btnGo.setIndeterminateProgressMode(true);

        if (!getItem(position).isRun()) {
            if (getItem(position).getHeaders() != "") {
                String header = getItem(position).getHeaders();
                String headerKey = header.split(":")[0].trim();
                String headerValue = header.split(":")[1].trim();
                Ion.with(getContext())
                        .load(getItem(position).getUrl() + getItem(position).getParams().replaceAll("#", "&"))
                        .setHeader(headerKey, headerValue)
                        .asJsonObject()
                        .setCallback(new FutureCallback<JsonObject>() {
                            @Override
                            public void onCompleted(Exception e, JsonObject result) {
                                try {
                                    // 获得返回JSON
                                    System.out.println(result.toString());
                                    vh.btnGo.setProgress(100);
                                    getItem(position).setRun(true);
                                    getItem(position).setResult(result.toString());
                                } catch (Exception ex) {
                                    System.out.println(ex.getMessage());
                                }
                            }
                        });
            } else {
                Ion.with(getContext())
                        .load(getItem(position).getUrl() + getItem(position).getParams().replaceAll("#", "&"))
                        .asJsonObject()
                        .setCallback(new FutureCallback<JsonObject>() {
                            @Override
                            public void onCompleted(Exception e, JsonObject result) {
                                try {
                                    // 获得返回JSON
                                    System.out.println(result.toString());
                                    vh.btnGo.setProgress(100);
                                    getItem(position).setRun(true);
                                    getItem(position).setResult(result.toString());
                                } catch (Exception ex) {
                                    System.out.println(ex.getMessage());
                                }
                            }
                        });
            }
        }


        //loader.setProgress(50);
        //vh.btnGo.setProgress(100);
        /*vh.btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                Toast.makeText(getContext(), "Button Clicked Position " +
                        position, Toast.LENGTH_SHORT).show();
            }
        });*/

        return convertView;
    }
    // 支持随机高度，暂时用固定高度0.218
    /*private double getPositionRatio(final int position) {
        double ratio = sPositionHeightRatios.get(position, 0.0);
        if (ratio == 0) {
            ratio = getRandomHeightRatio();
            sPositionHeightRatios.append(position, ratio);
            Log.d(TAG, "getPositionRatio:" + position + " ratio:" + ratio);
        }
        return ratio;
    }

    private double getRandomHeightRatio() {
        return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5 the width
    }*/

    /*private void updateProgressButton(ProgressButton progressButton, SeekBar progressSeekBar) {
        progressButton.setProgress(progressSeekBar.getProgress());
        updatePinProgressContentDescription(progressButton);
    }

    private void updatePinProgressContentDescription(ProgressButton button) {
        int progress = button.getProgress();
        if (progress <= 0) {
            button.setContentDescription(getString(
                    button.isChecked() ? R.string.content_desc_pinned_not_downloaded
                            : R.string.content_desc_unpinned_not_downloaded));
        } else if (progress >= button.getMax()) {
            button.setContentDescription(getString(
                    button.isChecked() ? R.string.content_desc_pinned_downloaded
                            : R.string.content_desc_unpinned_downloaded));
        } else {
            button.setContentDescription(getString(
                    button.isChecked() ? R.string.content_desc_pinned_downloading
                            : R.string.content_desc_unpinned_downloading));
        }
    }*/
}
